﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
//using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Collections;
using System.Text;
using FarPoint.Web.Spread;
using XMK.Tadong.Biz;
using Microsoft.Web.UI.WebControls;
using System.Web.UI.WebControls;

namespace XMK.Tadong.Web.TJ
{
    public partial class TJ_SYJL : System.Web.UI.Page
    {

        #region 界面组件
        //protected System.Web.UI.WebControls.CheckBoxList cbWell;
        //protected Microsoft.Web.UI.WebControls.TreeView TreeView1;
        //protected System.Web.UI.WebControls.CheckBoxList CheckBoxList1;
        //protected System.Web.UI.HtmlControls.HtmlSelect optionJH;
        //protected System.Web.UI.HtmlControls.HtmlTable Table2;
        //protected System.Web.UI.HtmlControls.HtmlTable Table3;
        //protected System.Web.UI.WebControls.CheckBoxList cblYCCW;
        //protected System.Web.UI.WebControls.Button btnNextYCCWStep;
        //protected System.Web.UI.WebControls.Button btnPreJHStep;
        //protected System.Web.UI.WebControls.Button btnNextStaticsStep;
        //protected System.Web.UI.HtmlControls.HtmlTable Table1;
        protected FarPoint.Web.Spread.FpSpread FpSpreadAS01;
        //protected System.Web.UI.HtmlControls.HtmlInputText selectedwells;


        //protected System.Web.UI.WebControls.Button btnPreSelYCCW;
        //protected System.Web.UI.WebControls.Button btnNextWellResult;
        //protected System.Web.UI.WebControls.Button btnPrevSelData;
        //protected System.Web.UI.WebControls.Button btnNextStatics;
        //protected System.Web.UI.WebControls.Button btnSaveStaticsData;
        //protected System.Web.UI.HtmlControls.HtmlTable Table4;
        //protected System.Web.UI.HtmlControls.HtmlTable Table5;
        //protected System.Web.UI.WebControls.Button btnDownloadData;
        //protected System.Web.UI.WebControls.RadioButtonList rblTXT;
        //protected System.Web.UI.WebControls.Button btnCalculate;
        //protected System.Web.UI.WebControls.Button btnPrevXmkResult;
        //protected System.Web.UI.WebControls.Literal Literal1;

        private FarPoint.Web.Spread.Model.DefaultSheetDataModel modelAs01;
        private FarPoint.Web.Spread.Model.DefaultSheetDataModel modelAs07;
        private FarPoint.Web.Spread.Model.DefaultSheetDataModel modelXmkResult;
        private FarPoint.Web.Spread.Model.DefaultSheetDataModel modelXmkAs01;


        protected System.Data.DataSet dsWellResult;
        protected System.Data.DataSet dsAS01;
        protected System.Data.DataSet dsAS07;
        protected FarPoint.Web.Spread.FpSpread FpSpreadAS07;
        protected FarPoint.Web.Spread.FpSpread FpSpreadWellResult;
        //protected FarPoint.Web.Spread.FpSpread FpSpreadXMKAS01;
        //protected System.Web.UI.WebControls.Button btnJH;
        //protected System.Web.UI.WebControls.Button btnCW;

        protected System.Data.DataSet dsXmk_AS01;
        protected System.Data.DataSet dsXmk_JH_AS01;
        protected System.Data.DataSet dsXmk_CW_AS01;
        private FarPoint.Web.Spread.Model.DefaultSheetDataModel modelXmk_JH_As01;
        //protected System.Web.UI.HtmlControls.HtmlTable Table6;
        //protected System.Web.UI.WebControls.Button btnCompareJHCW;
        //protected System.Web.UI.WebControls.Button btnPrevSYTJ;
        protected FarPoint.Web.Spread.FpSpread FpSpreadJH_XMKAS01;
        protected FarPoint.Web.Spread.FpSpread FpSpreadCW_XMKAS01;
        //protected System.Web.UI.WebControls.Button btnSaveJH;
        //protected System.Web.UI.WebControls.RadioButtonList rblJH;
        //protected System.Web.UI.WebControls.Button btnDownloadJH;
        //protected System.Web.UI.WebControls.Button btnSaveCW;
        //protected System.Web.UI.WebControls.RadioButtonList rblCW;
        //protected System.Web.UI.WebControls.Button btnDownloadCW;
        private FarPoint.Web.Spread.Model.DefaultSheetDataModel modelXmk_CW_As01;
        #endregion 界面组件

        private void Page_Load(object sender, System.EventArgs e)
        {
            //Response.Charset = "GB2312";
            //古108,英20,富33,富44,富42,芳176,英20,徐深902,五105,汪901,卫212,徐深3,古142,古145,古29,敖158,高171,芳35,朝59,大408,金392,古703,宋301,塔121,徐17,卫211,汪902,州311,州182,葡401,五104
            btnCalculate.Attributes.Add("OnClick", "Javascript:alert('计算过程比较复杂，将花费一定时间，请您耐心等待');");
            btnJH.Attributes.Add("OnClick", "Javascript:alert('计算过程比较复杂，将花费一定时间，请您耐心等待');");
            btnCW.Attributes.Add("OnClick", "Javascript:alert('计算过程比较复杂，将花费一定时间，请您耐心等待');");
            if (!IsPostBack)
            {
                //井号准备
                LoadTree();
                FilloptionJH();

                //油层准备
                //JrscSoft.BusinessService.GeoStatistics geoStatic = new JrscSoft.BusinessService.GeoStatistics();
                //this.cblYCCW.DataSource = geoStatic.GetYCCW();
                this.cblYCCW.DataTextField = "YCCW";
                this.cblYCCW.DataValueField = "YCCW";
                this.cblYCCW.DataMember = "YCCW";
                this.cblYCCW.DataBind();

                foreach (System.Web.UI.WebControls.ListItem li in this.cblYCCW.Items)
                {
                    li.Selected = true;
                }

                //所选井号
                ViewState["SelWell"] = "";

                //所选油层
                ViewState["SelYCCW"] = "";

                WhichShow(true, false, false, false, false, false);
            }


        }

     

        #region 井号选择
        /// <summary>
        /// 填充树盆地一级节点
        /// </summary>
        protected void LoadTree()
        {
            string strSql;
            string NodeType;
            NodeType = "1";
            string basinid = "";

            TreeView1.Nodes.Clear();
            //获取空间数据库连接字符串

            Microsoft.Web.UI.WebControls.TreeNode item1 = new Microsoft.Web.UI.WebControls.TreeNode();
            item1.Text = "项目库";
            
            TreeView1.Nodes.Add(item1);


            //查询出所有盆地，并在树上显示
            strSql = "select distinct basinname,basinid from gisbasin order by basinname";
            YQCJDBLL BLL = new YQCJDBLL();
            DataTable dTable = BLL.QueryData(strSql);
            for (int i = 0; i < dTable.Rows.Count; i++)
            {
                Microsoft.Web.UI.WebControls.TreeNode item = new Microsoft.Web.UI.WebControls.TreeNode();
                item.Text = dTable.Rows[i]["basinname"].ToString(); //"<span onmousemove=javascript:window.status=" + "'" + reader["basinname"].ToString() + "'" + ";   title="+ reader["basinname"].ToString() +"> "+ "<font color=blue>" + reader["basinname"].ToString() + "</font>" + "</span>";
                basinid = dTable.Rows[i]["basinid"].ToString();
                item.NavigateUrl = "JavaScript:OnWellInBasinorTectonicSelected(\"" + item.Text + "\",\"" + NodeType + "\")";
                item1.Nodes.Add(item);
                FillTreeAddTectonic(item,basinid);

            }

        }

        /// <summary>
        /// 填充树一级构造一级节点
        /// </summary>
        /// <param name="item"></param>
        /// <param name="basinid"></param>
        private void FillTreeAddTectonic(Microsoft.Web.UI.WebControls.TreeNode item, string basinid)
        {
            string strsql;
            string basinname = item.Text;
            string NodeType;
            NodeType = "2";
            string basinid1 = basinid;

            //查询出每一个盆地的下属所有一级构造，并在树上显示
            YQCJDBLL BLL = new YQCJDBLL();
            strsql = "select  basinid, name from gistectonic" + " " + "where  basinid=" + "'" + basinid1 + "'";
            DataTable dTable = BLL.QueryData(strsql);

            for (int i = 0; i < dTable.Rows.Count; i++)
            {
                Microsoft.Web.UI.WebControls.TreeNode item1 = new Microsoft.Web.UI.WebControls.TreeNode();
                item1.Text = dTable.Rows[i]["name"].ToString(); // "<span onmousemove=javascript:window.status=" + "'" + reader["name"].ToString() + "'" + ";   title="+ reader["name"].ToString() +"> "+ "<font color=red>" + reader["name"].ToString() + "</font>" + "</span>";
                item.Nodes.Add(item1);
                item1.NavigateUrl = "JavaScript:OnWellInBasinorTectonicSelected(\"" + item1.Text + "\",\"" + NodeType + "\")";
            }
        }

        /// <summary>
        /// 将井姓填充到Select列表中
        /// </summary>
        private void FilloptionJH()
        {
            string strsql;

            string wellname = "";
            //连接数据库 
            YQCJDBLL BLL = new YQCJDBLL();
            //查询出盆地上所有井的井姓
            strsql = "select distinct substr(jh,0,1) as wellxing from giswell";
            //this.optionJH.Items.Add(" ");
            this.optionJH.Items.Add("全部");
            DataTable dTable = BLL.QueryData(strsql);
           
            for (int i = 0; i < dTable.Rows.Count; i++)
            {
                wellname = dTable.Rows[i]["wellxing"].ToString().Trim();
                this.optionJH.Items.Add(wellname);
            }
        }
        #endregion

        #region 公共函数
        /// <summary>
        /// 显示消息窗口
        /// </summary>
        /// <param name="p_strShowMessage"></param>
        public void showMessage(string p_strShowMessage)
        {
            Page.ClientScript.RegisterClientScriptInclude("01", "<script language=javascript> alert('" + p_strShowMessage + "')</script>");
        }

        /// <summary>
        /// 显示哪个表格
        /// </summary>
        /// <param name="tbl1"></param>
        /// <param name="tbl2"></param>
        /// <param name="tbl3"></param>
        public void WhichShow(bool tbl1, bool tbl2, bool tbl3)
        {
            ViewState["SelWell"] = selectedwells.Value;

            Table1.Visible = false;
            Table2.Visible = false;
            Table3.Visible = false;

            if (tbl1)
            {
                selectedwells.Value = ViewState["SelWell"].ToString();

                Table1.Visible = true;
                Table1.Attributes.Add("style", "Left:1px;top:6px");
            }
            if (tbl2)
            {
                Table2.Visible = true;
                Table2.Attributes.Add("style", "Left:1px;top:6px");
            }
            if (tbl3)
            {
                Table3.Visible = true;
                Table3.Attributes.Add("style", "Left:1px;top:6px");

            }
        }
        /// <summary>
        /// 显示哪个表格
        /// </summary>
        /// <param name="tbl1"></param>
        /// <param name="tbl2"></param>
        /// <param name="tbl3"></param>
        public void WhichShow(bool tbl1, bool tbl2, bool tbl3, bool tbl4, bool tbl5)
        {
            ViewState["SelWell"] = selectedwells.Value;

            Table1.Visible = false;
            Table2.Visible = false;
            Table3.Visible = false;
            Table4.Visible = false;
            Table5.Visible = false;

            if (tbl1)
            {
                selectedwells.Value = ViewState["SelWell"].ToString();

                Table1.Visible = true;
                Table1.Attributes.Add("style", "Left:1px;top:6px");
            }
            if (tbl2)
            {
                Table2.Visible = true;
                Table2.Attributes.Add("style", "Left:1px;top:6px");
            }
            if (tbl3)
            {
                Table3.Visible = true;
                Table3.Attributes.Add("style", "Left:1px;top:6px");

            }
            if (tbl4)
            {
                Table4.Visible = true;
                Table4.Attributes.Add("style", "Left:1px;top:6px");

            }
            if (tbl5)
            {
                Table5.Visible = true;
                Table5.Attributes.Add("style", "Left:1px;top:6px");

            }
        }
        /// <summary>
        /// 显示哪个表格
        /// </summary>
        /// <param name="tbl1"></param>
        /// <param name="tbl2"></param>
        /// <param name="tbl3"></param>
        public void WhichShow(bool tbl1, bool tbl2, bool tbl3, bool tbl4, bool tbl5, bool tbl6)
        {
            ViewState["SelWell"] = selectedwells.Value;

            Table1.Visible = false;
            Table2.Visible = false;
            Table3.Visible = false;
            Table4.Visible = false;
            Table5.Visible = false;
            Table6.Visible = false;

            if (tbl1)
            {
                selectedwells.Value = ViewState["SelWell"].ToString();

                Table1.Visible = true;
                Table1.Attributes.Add("style", "Left:1px;top:6px");
            }
            if (tbl2)
            {
                Table2.Visible = true;
                Table2.Attributes.Add("style", "Left:1px;top:6px");
            }
            if (tbl3)
            {
                Table3.Visible = true;
                Table3.Attributes.Add("style", "Left:1px;top:6px");

            }
            if (tbl4)
            {
                Table4.Visible = true;
                Table4.Attributes.Add("style", "Left:1px;top:6px");

            }
            if (tbl5)
            {
                Table5.Visible = true;
                Table5.Attributes.Add("style", "Left:1px;top:6px");

            }
            if (tbl6)
            {
                Table6.Visible = true;
                Table6.Attributes.Add("style", "Left:1px;top:6px");

            }
        }

        //		#region 图形绘制
        //		/// <summary>
        //		/// 图形绘制
        //		/// </summary>
        //		/// <param name="sqlstr"></param>
        //		/// <param name="title"></param>
        //		private void GetStatPicure(string sqlstr,string title)
        //		{
        //			Literal1.Text ="";
        //			string strLine="";
        //			strLine += "<script  LANGUAGE=javascript>";
        //			strLine += "\r\n";
        //			strLine += "<!--";
        //			strLine += "\r\n";
        //			strLine += "function btnDrawMap_click(){";
        //			strLine += "\r\n";
        //			//			strLine+="frmSYTJ.VcChart1.RowCount=4";
        //			//			strLine += "\r\n";
        //			//			strLine+="frmSYTJ.VcChart1.ColumnCount=6";
        //
        //
        //			//string str="select CW,HD,MAX,MIN,AVER,LJHD,SDB from xmk_a_z_ny01 where jh='敖10'";
        //			DataSet ds=serclient.GetDataSet (sqlstr);
        //			// gChartType=
        //		
        //			//object[] arr=null;
        //			int numRow=ds.Tables [0].Rows .Count ;
        //			int numCol=ds.Tables [0].Columns .Count ;
        //
        //			//title="敖1";
        //			
        //
        //			strLine += "\r\n";
        //			strLine+="frmSYTJ.VcChart1.RowCount ="+(short)numRow+";";
        //			strLine += "\r\n";
        //			strLine+="frmSYTJ.VcChart1.ColumnCount ="+(short)(numCol-1)+";";
        //			strLine+="\r\n";
        //			//strLine+="frmSYTJ.VcChart1.ColumnCount ="+(short)(numCol-1)+"";
        //			strLine+="\r\n";
        //
        //			for(int i=0;i<numRow;i++)
        //			{
        //							
        //				for(int j=1;j<numCol;j++)
        //				{
        //					strLine+="frmSYTJ.VcChart1.Row ="+(short)(i+1)+";";
        //					strLine += "\r\n";
        //					strLine+="frmSYTJ.VcChart1.Column ="+(short)j+";";
        //					strLine += "\r\n";
        //					strLine+="frmSYTJ.VcChart1.Data =\""+ds.Tables [0].Rows [i][j].ToString ()+"\";";
        //					strLine += "\r\n";
        //					//strLine+= "frmSYTJ.VcChart1.DataGrid .SetData(Form1.VcChart1.Row ,Form1.VcChart1.Column ,0,false);";
        //					strLine += "\r\n";
        //					strLine+= "";
        //					strLine += "\r\n";
        //					strLine+="frmSYTJ.VcChart1.ColumnLabel =\""+ds.Tables[0].Columns [j].ColumnName+"\";";
        //					strLine += "\r\n";
        //					strLine+="frmSYTJ.VcChart1.RowLabel=\""+ds.Tables [0].Rows [i][0].ToString ()+"\";";
        //					strLine += "\r\n";			
        //							
        //				}
        //			}
        //			string title_new=title+"试油结论统计";
        //			//    
        //			strLine += "\r\n";
        //			strLine+="frmSYTJ.VcChart1.Title .Text  =\""+title_new+"\";";
        //
        //			strLine += "\r\n";
        //			strLine+="frmSYTJ.VcChart1.Legend.Location.Visible =true;";
        //			strLine += "\r\n";
        //			strLine+="frmSYTJ.VcChart1.Title .Font .Size =15;";
        //			strLine += "\r\n";
        //			strLine+="frmSYTJ.VcChart1.Title .Font.Bold =true;";
        //			strLine += "\r\n";
        //			strLine+="frmSYTJ.VcChart1.Legend.Font .Size =10;";
        //
        //			strLine += "\r\n";
        //			strLine += "}";
        //			strLine += "\r\n";
        //			strLine = strLine + "document.frmSYTJ.btnDrawMap.style.visibility = \"visible\";";
        //			strLine += "\r\n";
        //			Literal1.Text ="";		
        //		
        //			strLine += "-->";
        //			strLine += "\r\n";
        //			strLine +="</script>";
        //			strLine += "\r\n";
        //			Literal1.Text = strLine; 			
        //
        //		}
        //		#endregion
        #endregion

        #region 试油结论统计计算步骤
        /// <summary>
        /// 油层选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NextSelYCCW_Click(object sender, System.EventArgs e)
        {

            string strWell = selectedwells.Value;//ViewState["SelWell"].ToString();
            if (strWell.Length == 0)
            {
                this.showMessage("请选取要进行统计的井号");
                return;
            }
            //分割计算提供了多少口井
            string delimStr = ",";
            char[] delimiter = delimStr.ToCharArray();

            string[] strWells = strWell.Split(delimiter); ;

            if (strWells.Length > 999)
            {
                this.showMessage("您提供的井号超过了1000个,请您重新选择需要计算的井号");
                return;
            }

            WhichShow(false, true, false, false, false);

        }
        /// <summary>
        /// 开始统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextStaticsStep_Click(object sender, System.EventArgs e)
        {
            WhichShow(false, false, true, false, false);
            ViewState["SelYCCW"] = "";
            string strYCCW = "";
            foreach (System.Web.UI.WebControls.ListItem li in cblYCCW.Items)
            {
                if (li.Selected)
                {
                    strYCCW += li.Value + ",";
                }
            }
            if (strYCCW.Length != 0)
            {
                strYCCW = strYCCW.Substring(0, strYCCW.Length - 1);
            }
            strYCCW = "'" + strYCCW.Replace(",", "','") + "'";
            strYCCW = strYCCW.ToUpper();
            ViewState["SelYCCW"] = strYCCW;

            string strWell = ViewState["SelWell"].ToString();
            if (strWell.Length == 0)
            {
                this.showMessage("请选取要进行统计的井号");
                return;
            }
            if (strYCCW.Length == 0)
            {
                this.showMessage("请选取要进行统计的层位");
                return;
            }
            strWell = "'" + strWell.Replace(",", "','") + "'";
            //提取AS01和AS07数据
            string strSqlAs01 = string.Format("select  jh,xh,c.criterion,t.yccw,t.ch,t.djsd1,t.djsd2,nvl(t.djsd2,0) - nvl(t.djsd1,0) as HD,(nvl(t.djsd2,0) + nvl(t.djsd1,0))/2 as YCZB,getmaxvalue(nvl(t.rcyl1,0),nvl(t.rcyl2,0),nvl(t.rcyl3,0),nvl(t.rcyl4,0),nvl(t.rcyl5,0),nvl(t.rcyl6,0)) as RCYL,getmaxvalue(nvl(t.rcql1,0),nvl(t.rcql2,0),nvl(rcql3,0),nvl(t.rcql4,0),nvl(t.rcql5,0),nvl(t.rcql6,0)) as RCQL,getmaxvalue(nvl(t.rcsl1,0),nvl(t.rcsl2,0),nvl(t.rcsl3,0),nvl(t.rcsl4,0),nvl(t.rcsl5,0),nvl(t.rcsl6,0)) as RCSL,t.syjl from as01 t ,xmk_criterion c where upper(trim(t.yccw))=upper(trim(c.value)) and upper(trim(c.criterion)) in ({0}) and t.jh in ({1})", strYCCW, strWell);
            string strSqlAs07 = string.Format("select  jh,xh,c.criterion,t.yccw,t.ch,t.djsd1,t.djsd2,nvl(t.djsd2,0) - nvl(t.djsd1,0) as HD,(nvl(t.djsd2,0) + nvl(t.djsd1,0))/2 as YCZB,get2maxvalue(nvl(t.scrcyl,0),nvl(t.zsrcyl,0)) as RCYL,nvl(t.rcql,0) as rcql,get2maxvalue(nvl(t.scrcsl,0),nvl(t.zsrcsl,0)) as RCSL ,nvl(t.csjl,0) as csjl from as07 t ,xmk_criterion c where upper(trim(t.yccw))=upper(trim(c.value)) and upper(trim(c.criterion)) in ({0}) and t.jh in ({1})", strYCCW, strWell);

            //JrscSoft.DataService.DataService dService = new JrscSoft.DataService.DataService();
            YQCJDBLL bll = new YQCJDBLL();
            this.dsAS07 = bll.GetData(strSqlAs07);
            this.dsAS01 = bll.GetData(strSqlAs01);

            InitSpreadForAs01();
            InitSpreadForAs07();
        }

        /// <summary>
        /// 回退到井号选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreJHStep_Click(object sender, System.EventArgs e)
        {
            WhichShow(true, false, false, false, false);
        }

        private void btnPreSelYCCW_Click(object sender, System.EventArgs e)
        {
            WhichShow(false, true, false, false, false);
        }

        private void btnNextWellResult_Click(object sender, System.EventArgs e)
        {
            //保存的当前修改后的数据集
            this.dsAS01 = (System.Data.DataSet)this.FpSpreadAS01.ActiveSheetView.DataSource;
            this.dsAS07 = (System.Data.DataSet)this.FpSpreadAS07.ActiveSheetView.DataSource;

            ViewState["dsAS01"] = dsAS01;
            ViewState["dsAS07"] = dsAS07;
            WhichShow(false, false, false, true, false);

            //初始化产能标准
            string strSql = "select t.id,t.jb,t.COMPARE,t.result,t.depthmax,t.depthmin,nvl(t.oil_max,0) as oil_max,nvl(t.oil_min,0) as oil_min ,nvl(t.gas_max,0) as gas_max,nvl(t.gas_min,0) as gas_min,nvl(t.water_max,0) as water_max,nvl(t.water_min,0) as water_min from xmk_wellresult t order by jb";
            //JrscSoft.DataService.DataService dService = new JrscSoft.DataService.DataService();
            //this.dsWellResult = dService.GetDataset(strSql);
            InitSpreadForWellResult();

        }

        private void btnNextStatics_Click(object sender, System.EventArgs e)
        {
            //越过产能标准
            WhichShow(false, false, false, false, true);

            //保存当前产能标准修改值
            this.dsWellResult = (System.Data.DataSet)this.FpSpreadWellResult.ActiveSheetView.DataSource;
            ViewState["WellResult"] = this.dsWellResult;
        }

        private void btnPrevSelData_Click(object sender, System.EventArgs e)
        {
            WhichShow(false, false, true, false, false);
        }
        private void btnPrevXmkResult_Click(object sender, System.EventArgs e)
        {
            WhichShow(false, false, false, true, false);
        }
        private void btnCompareJHCW_Click(object sender, System.EventArgs e)
        {
            this.WhichShow(false, false, false, false, false, true);
        }

        private void btnPrevSYTJ_Click(object sender, System.EventArgs e)
        {
            this.WhichShow(false, false, false, false, true, false);
        }

        #endregion

        #region AS07 相关操作

        private void InitSpreadForAs07()
        {
            modelAs07 = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(dsAS07, "");
            this.FpSpreadAS07.Sheets[0].DataModel = modelAs07;
            this.FpSpreadAS07.DataBind();

            FpSpreadAS07.ActiveSheetView.AllowSort = true;
            FpSpreadAS07.ActiveSheetView.SetColumnSortIndicator(1, FarPoint.Web.Spread.Model.SortIndicator.Descending);

            FpSpreadAS07.Sheets[0].AllowDelete = true;
            FpSpreadAS07.Sheets[0].AllowInsert = true;

        }

        private void FpSpreadAS07_UpdateCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
        {
            object strvalue;
            int row = (int)e.CommandArgument;
            int colcnt = e.EditValues.Count;
            for (int i = 0; i < colcnt; i++)
            {
                if (!Object.ReferenceEquals(e.EditValues[i], FarPoint.Web.Spread.FpSpread.Unchanged))
                {
                    strvalue = e.EditValues[i];
                    if (strvalue.ToString() != "")
                        FpSpreadAS07.ActiveSheetView.SetValue(row, i, strvalue);
                    else
                    {
                        FpSpreadAS07.ActiveSheetView.SetValue(row, i, null);
                    }
                }
                strvalue = null;
            }
            e.Handled = true;

            System.Data.DataSet dds = (System.Data.DataSet)FpSpreadAS07.ActiveSheetView.DataSource;
            this.dsAS07 = dds;

            ViewState["dsAS07"] = dds;

        }


        #endregion

        #region AS01 相关操作

        private void InitSpreadForAs01()
        {
            modelAs01 = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(dsAS01, "");
            this.FpSpreadAS01.Sheets[0].DataModel = modelAs01;
            this.FpSpreadAS01.DataBind();

            FpSpreadAS01.ActiveSheetView.AllowSort = true;
            FpSpreadAS01.ActiveSheetView.SetColumnSortIndicator(1, FarPoint.Web.Spread.Model.SortIndicator.Descending);

            FpSpreadAS01.Sheets[0].AllowDelete = true;
            FpSpreadAS01.Sheets[0].AllowInsert = true;
        }
        private void FpSpreadAS01_CreateButton(object sender, FarPoint.Web.Spread.CreateButtonEventArgs e)
        {

            if (e.Command == "Update")
            {
                e.Label = "保存";
            }
            if (e.Command == "Cancel")
            {
                e.Label = "取消";
            }
            if (e.Command == "Clear")
            {
                e.Label = "剪切";
            }
            if (e.Command == "Copy")
            {
                e.Label = "复制";
            }
            if (e.Command == "Paste")
            {
                e.Label = "粘贴";
            }
            if (e.Command == "Add")
            {
                e.Label = "追加";
            }
            if (e.Command == "Insert")
            {
                e.Label = "插入";
            }
            if (e.Command == "Delete")
            {
                e.Label = "删除";
            }
            if (e.Command == "Print")
            {
                e.Label = "打印";
            }
            if (e.Command == "Prev")
            {
                e.Label = "上页";
            }
            if (e.Command == "Next")
            {
                e.Label = "下页";
            }
        }

        private void FpSpreadAS01_UpdateCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
        {
            object strvalue;
            int row = (int)e.CommandArgument;
            int colcnt = e.EditValues.Count;
            for (int i = 0; i < colcnt; i++)
            {
                if (!Object.ReferenceEquals(e.EditValues[i], FarPoint.Web.Spread.FpSpread.Unchanged))
                {
                    strvalue = e.EditValues[i];
                    if (strvalue.ToString() != "")
                        FpSpreadAS01.ActiveSheetView.SetValue(row, i, strvalue);
                    else
                    {
                        FpSpreadAS01.ActiveSheetView.SetValue(row, i, null);
                    }
                }
                strvalue = null;
            }
            e.Handled = true;

            System.Data.DataSet dds = (System.Data.DataSet)FpSpreadAS01.ActiveSheetView.DataSource;
            this.dsAS01 = dds;

            ViewState["dsAS01"] = dds;
        }

        private void FpSpreadAS01_InsertCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
        {
            string strvalue;
            int row = (int)e.CommandArgument;
            int colcnt = e.EditValues.Count;
            this.modelAs01.AddRow(row);
            for (int i = 0; i < colcnt; i++)
            {
                if (!Object.ReferenceEquals(e.EditValues[i], FarPoint.Web.Spread.FpSpread.Unchanged))
                {
                    strvalue = e.EditValues[i].ToString();
                    FpSpreadAS01.ActiveSheetView.SetValue(row, i, strvalue);
                }
                strvalue = "";
            }
            e.Handled = true;

            System.Data.DataSet dds = (System.Data.DataSet)FpSpreadAS01.ActiveSheetView.DataSource;
            this.dsAS01 = dds;
        }

        private void FpSpreadAS01_DeleteCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
        {
            int row = (int)e.CommandArgument;
            this.modelAs01.RemoveRow(row);

            e.Handled = true;

            System.Data.DataSet dds = (System.Data.DataSet)FpSpreadAS01.ActiveSheetView.DataSource;
            this.dsAS01 = dds;
        }

        private void FpSpreadAS01_SaveOrLoadSheetState(object sender, FarPoint.Web.Spread.SheetViewStateEventArgs e)
        {
            if (e.IsSave)
            {
                FpSpreadAS01.Page.Session["ViewState"] = e.SheetView.SaveViewState();
            }
            else
            {
                e.SheetView.LoadViewState(FpSpreadAS01.Page.Session["ViewState"]);

            }
            e.Handled = true;
        }
        #endregion

        #region 产能标准 相关操作
        private void InitSpreadForWellResult()
        {
            if (ViewState["WellResult"] != null)
                dsWellResult = (System.Data.DataSet)ViewState["WellResult"];
            modelXmkResult = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(dsWellResult, "");
            this.FpSpreadWellResult.Sheets[0].DataModel = modelXmkResult;
            this.FpSpreadWellResult.DataBind();

            FpSpreadWellResult.ActiveSheetView.AllowSort = true;
            FpSpreadWellResult.ActiveSheetView.SetColumnSortIndicator(1, FarPoint.Web.Spread.Model.SortIndicator.Descending);

            FpSpreadWellResult.Sheets[0].AllowDelete = true;
            FpSpreadWellResult.Sheets[0].AllowInsert = true;

        }
        private void FpSpreadWellResult_UpdateCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
        {
            object strvalue;
            int row = (int)e.CommandArgument;
            int colcnt = e.EditValues.Count;
            for (int i = 0; i < colcnt; i++)
            {
                if (!Object.ReferenceEquals(e.EditValues[i], FarPoint.Web.Spread.FpSpread.Unchanged))
                {
                    strvalue = e.EditValues[i];
                    if (strvalue.ToString() != "")
                        FpSpreadWellResult.ActiveSheetView.SetValue(row, i, strvalue);
                    else
                    {
                        FpSpreadWellResult.ActiveSheetView.SetValue(row, i, null);
                    }
                }
                strvalue = null;
            }
            e.Handled = true;

            System.Data.DataSet dds = (System.Data.DataSet)FpSpreadWellResult.ActiveSheetView.DataSource;
            this.dsWellResult = dds;

            ViewState["WellResult"] = dds;
        }

        #endregion

        #region 试油计算结果 相关操作


        private void btnCalculate_Click(object sender, System.EventArgs e)
        {
            DataTable dTable = new DataTable("Xmk_Temp_As01");

            DataColumn JhCol = dTable.Columns.Add("JH", typeof(String));
            JhCol.AllowDBNull = false;
            JhCol.Unique = false;

            DataColumn XhCol = dTable.Columns.Add("Xh", typeof(String));
            XhCol.AllowDBNull = false;
            XhCol.Unique = false;

            DataColumn YccwCol = dTable.Columns.Add("criterion", typeof(String));
            YccwCol.AllowDBNull = false;
            YccwCol.Unique = false;

            dTable.Columns.Add("CW", typeof(String));
            dTable.Columns.Add("CH", typeof(String));
            dTable.Columns.Add("DJSD1", typeof(Double));
            dTable.Columns.Add("DJSD2", typeof(Double));
            dTable.Columns.Add("HD", typeof(Double));
            dTable.Columns.Add("YCZB", typeof(Double));
            dTable.Columns.Add("RCYL", typeof(Double));
            dTable.Columns.Add("RCQL", typeof(Double));
            dTable.Columns.Add("RCSL", typeof(Double));
            dTable.Columns.Add("SYJL", typeof(String));
            dTable.Columns.Add("JSJG", typeof(String));
            dTable.Columns.Add("JB", typeof(int));
            dTable.Columns.Add("COMPARE", typeof(String));

            int JB = 0;
            string COMPARE = "-";

            //DataTable dAs01Table = ((System.Data.DataSet)this.FpSpreadAS01.ActiveSheetView.DataSource).Tables[0];
            DataTable dAs01Table = ((System.Data.DataSet)ViewState["dsAS01"]).Tables[0];
            foreach (DataRow dRow in dAs01Table.Rows)
            {
                DataRow dNewRow = dTable.NewRow();
                dNewRow["JH"] = dRow["JH"] != null ? dRow["JH"].ToString() : "";
                dNewRow["XH"] = dRow["XH"] != null ? dRow["XH"].ToString() : "";
                dNewRow["criterion"] = dRow["criterion"] != null ? dRow["criterion"].ToString() : "";
                dNewRow["CW"] = dRow["YCCW"] != null ? dRow["YCCW"].ToString() : "";
                dNewRow["CH"] = dRow["CH"] != null ? dRow["CH"].ToString() : "";
                dNewRow["DJSD1"] = dRow["DJSD1"] != null ? dRow["DJSD1"].ToString() : "";
                dNewRow["DJSD2"] = dRow["DJSD2"] != null ? dRow["DJSD2"].ToString() : "";
                dNewRow["YCZB"] = dRow["YCZB"] != null ? dRow["YCZB"].ToString() : "";
                dNewRow["HD"] = dRow["HD"] != null ? dRow["HD"].ToString() : "";
                dNewRow["RCYL"] = dRow["RCYL"] != null ? dRow["RCYL"].ToString() : "";
                dNewRow["RCQL"] = dRow["RCQL"] != null ? dRow["RCQL"].ToString() : "";
                dNewRow["RCSL"] = dRow["RCSL"] != null ? dRow["RCSL"].ToString() : "";
                dNewRow["SYJL"] = dRow["SYJL"] != null ? dRow["SYJL"].ToString() : "";
                dNewRow["JSJG"] = this.ComputeYQSValue(Convert.ToDouble(dNewRow["DJSD1"]), Convert.ToDouble(dNewRow["RCYL"]), Convert.ToDouble(dNewRow["RCQL"]), Convert.ToDouble(dNewRow["RCSL"]), out JB, out COMPARE);
                dNewRow["JB"] = JB;
                dNewRow["COMPARE"] = COMPARE;
                dTable.Rows.Add(dNewRow);
            }

            JB = 0;
            COMPARE = "-";

            //DataTable dAs07Table = ((System.Data.DataSet)this.FpSpreadAS07.ActiveSheetView.DataSource).Tables[0];
            DataTable dAs07Table = ((System.Data.DataSet)ViewState["dsAS07"]).Tables[0];
            foreach (DataRow dRow in dAs07Table.Rows)
            {
                DataRow dNewRow = dTable.NewRow();
                dNewRow["JH"] = dRow["JH"] != null ? dRow["JH"].ToString() : "";
                dNewRow["XH"] = dRow["XH"] != null ? dRow["XH"].ToString() : "";
                dNewRow["criterion"] = dRow["criterion"] != null ? dRow["criterion"].ToString() : "";
                dNewRow["CW"] = dRow["YCCW"] != null ? dRow["YCCW"].ToString() : "";
                dNewRow["CH"] = dRow["CH"] != null ? dRow["CH"].ToString() : "";
                dNewRow["DJSD1"] = dRow["DJSD1"] != null ? dRow["DJSD1"].ToString() : "";
                dNewRow["DJSD2"] = dRow["DJSD2"] != null ? dRow["DJSD2"].ToString() : "";
                dNewRow["YCZB"] = dRow["YCZB"] != null ? dRow["YCZB"].ToString() : "";
                dNewRow["HD"] = dRow["HD"] != null ? dRow["HD"].ToString() : "";
                dNewRow["RCYL"] = dRow["RCYL"] != null ? dRow["RCYL"].ToString() : "";
                dNewRow["RCQL"] = dRow["RCQL"] != null ? dRow["RCQL"].ToString() : "";
                dNewRow["RCSL"] = dRow["RCSL"] != null ? dRow["RCSL"].ToString() : "";
                dNewRow["SYJL"] = dRow["CSJL"] != null ? dRow["CSJL"].ToString() : "";
                dNewRow["JSJG"] = this.ComputeYQSValue(Convert.ToDouble(dNewRow["DJSD1"]), Convert.ToDouble(dNewRow["RCYL"]), Convert.ToDouble(dNewRow["RCQL"]), Convert.ToDouble(dNewRow["RCSL"]), out JB, out COMPARE);
                dNewRow["JB"] = JB;
                dNewRow["COMPARE"] = COMPARE;
                dTable.Rows.Add(dNewRow);
            }

            dsXmk_AS01 = new DataSet();

            this.dsXmk_AS01.Tables.Add(dTable);

            InitSpreadForXmk_As01();

            btnSaveStaticsData.Enabled = true;
            btnDownloadData.Enabled = true;
            rblTXT.Enabled = true;
            FpSpreadXMKAS01.Visible = true;

            //按井号层位优选
            btnCompareJHCW.Enabled = true;

            //合并结果相关控件显示
            btnJH.Enabled = true;
            btnCW.Enabled = true;

        }

        private void InitSpreadForXmk_As01()
        {
            this.modelXmkAs01 = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(dsXmk_AS01, "");
            this.FpSpreadXMKAS01.Sheets[0].DataModel = modelXmkAs01;
            this.FpSpreadXMKAS01.DataBind();

            FpSpreadXMKAS01.ActiveSheetView.AllowSort = true;
            FpSpreadXMKAS01.ActiveSheetView.SetColumnSortIndicator(1, FarPoint.Web.Spread.Model.SortIndicator.Descending);

            FpSpreadXMKAS01.Sheets[0].AllowDelete = true;
            FpSpreadXMKAS01.Sheets[0].AllowInsert = true;
        }

        /// <summary>
        /// 试油结论计算核心算法
        /// 其他主要算法在数据库建表和选数据中体现了
        /// 根据传入的DJSD1大于等于最小深度，小于最大深度
        /// DJSD1 小于 depthmax && DJSD2 大于等于 DJSD1
        /// </summary>
        /// <param name="DJSD1"></param>
        /// <param name="RCYL"></param>
        /// <param name="RCQL"></param>
        /// <param name="RCSL"></param>
        /// <returns></returns>
        private string ComputeYQSValue(double DJSD1, double RCYL, double RCQL, double RCSL, out int JB, out string COMPARE)
        {
            JB = 0;
            COMPARE = "-";
            string strValue = "";
            string strDepth = string.Format("depthmax > {0} And depthmin <= {0} And Oil_Max > {1}  And Oil_Min <= {1} And GAS_MAX > {2} And GAS_MIN <= {2} And WATER_MAX > {3} And Water_Min <= {3}", DJSD1, RCYL, RCQL, RCSL);
            DataSet dsXmkResult = (System.Data.DataSet)ViewState["WellResult"];
            DataTable dtXmkResult = dsXmkResult.Tables[0];
            DataRow[] drXmkResult = dtXmkResult.Select(strDepth);

            for (int i = 0; i < drXmkResult.Length; i++)
            {
                JB = Convert.ToInt32(drXmkResult[i].ItemArray.GetValue(1).ToString());
                strValue = drXmkResult[i].ItemArray.GetValue(3).ToString();
                COMPARE = drXmkResult[i].ItemArray.GetValue(2).ToString();
            }
            return strValue;
        }

        private void btnDownloadData_Click(object sender, System.EventArgs e)
        {
            string pathName = HttpContext.Current.Server.MapPath(Request.ApplicationPath + "/") + System.Configuration.ConfigurationSettings.AppSettings["tmpDown"].ToString() + "/" + Session["UserCode"].ToString() + "/";
            if (!Directory.Exists(pathName))
            {
                Directory.CreateDirectory(pathName);
            }

            string strFileName = pathName + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + "." + rblTXT.SelectedValue;

            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
            }

            bool bSaved = false;
            if (rblTXT.SelectedValue == "xls")
            {

                //自带表头
                bSaved = this.FpSpreadXMKAS01.SaveExcel(strFileName, FarPoint.Web.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);

                //特殊处理带表头
                //				DataGrid drgCase_temp = new DataGrid() ;
                //                DataSet dsDownData = (DataSet)this.FpSpreadXMKAS01.ActiveSheetView.DataSource;
                //				drgCase_temp.DataSource = dsDownData.Tables[0].DefaultView;
                //                drgCase_temp.DataBind();
                //				ExportDataGrid(drgCase_temp,"application/ms-excel",DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")+".xls"); 

            }
            else
            {
                bSaved = this.FpSpreadXMKAS01.ActiveSheetView.SaveTextFile(strFileName, false, FarPoint.Web.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly, "\r", ";", "");
            }

            if (bSaved)
            {
                //下载传输文件
                string szFileName = Path.GetFileNameWithoutExtension(strFileName);
                strFileName = strFileName.Replace("\\", "*").Replace("/", "*").Replace(" ", "-");
                string strDownUrl = "../CommonPage/DownFile.aspx?FileName='+escape('" + szFileName + "')" + "+'&'+" + "'FilePath=' +escape('" + strFileName + "')";
                Response.Write("<script language='javascript'>window.open('" + strDownUrl + ",'_blank','toolbar=no,directories=no,menubar=no,status=no,width=1,height=1,left=0,top=0');</script>");
            }
            else
            {
                this.showMessage("服务器写文件出现错误，请联系软件技术支持检查文件是否可写或代码错误");
            }
        }
        /// <summary>
        /// 导出查询出来的网格数据
        /// </summary>
        /// <param name="dgField_parm"></param>
        /// <param name="FileType"></param>
        /// <param name="FileName"></param>
        private void ExportDataGrid(DataGrid dgField_parm, string FileType, string FileName)
        {
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
            Response.ContentType = FileType;
            this.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);

            dgField_parm.RenderControl(hw);

            Response.Write(tw.ToString());
            Response.End();
        }

        private void btnSaveStaticsData_Click(object sender, System.EventArgs e)
        {

        }

        #endregion

        #region 按井号优选试油结论数据
        private void btnDownloadJH_Click(object sender, System.EventArgs e)
        {
            string pathName = HttpContext.Current.Server.MapPath(Request.ApplicationPath + "/") + System.Configuration.ConfigurationSettings.AppSettings["tmpDown"].ToString() + "/" + Session["UserCode"].ToString() + "/";
            if (!System.IO.Directory.Exists(pathName))
            {
                System.IO.Directory.CreateDirectory(pathName);
            }

            string strFileName = pathName + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + "." + rblJH.SelectedValue;

            if (System.IO.File.Exists(strFileName))
            {
                System.IO.File.Delete(strFileName);
            }

            bool bSaved = false;
            if (rblJH.SelectedValue == "xls")
            {

                //自带表头
                bSaved = this.FpSpreadJH_XMKAS01.SaveExcel(strFileName, FarPoint.Web.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);

                //特殊处理带表头
                //				DataGrid drgCase_temp = new DataGrid() ;
                //                DataSet dsDownData = (DataSet)this.FpSpreadXMKAS01.ActiveSheetView.DataSource;
                //				drgCase_temp.DataSource = dsDownData.Tables[0].DefaultView;
                //                drgCase_temp.DataBind();
                //				ExportDataGrid(drgCase_temp,"application/ms-excel",DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")+".xls"); 

            }
            else
            {
                bSaved = this.FpSpreadJH_XMKAS01.ActiveSheetView.SaveTextFile(strFileName, false, FarPoint.Web.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly, "\r", ";", "");
            }

            if (bSaved)
            {
                //下载传输文件
                string szFileName = System.IO.Path.GetFileNameWithoutExtension(strFileName);
                strFileName = strFileName.Replace("\\", "*").Replace("/", "*").Replace(" ", "-");
                string strDownUrl = "../CommonPage/DownFile.aspx?FileName='+escape('" + szFileName + "')" + "+'&'+" + "'FilePath=' +escape('" + strFileName + "')";
                Response.Write("<script language='javascript'>window.open('" + strDownUrl + ",'_blank','toolbar=no,directories=no,menubar=no,status=no,width=1,height=1,left=0,top=0');</script>");
            }
            else
            {
                this.showMessage("服务器写文件出现错误，请联系软件技术支持检查文件是否可写或代码错误");
            }
        }



        private void btnJH_Click(object sender, System.EventArgs e)
        {
            //准备数据表存储
            DataTable dTable = new DataTable("Xmk_Temp_As01");

            DataColumn JhCol = dTable.Columns.Add("JH", typeof(String));
            JhCol.AllowDBNull = false;
            JhCol.Unique = false;

            DataColumn XhCol = dTable.Columns.Add("Xh", typeof(String));
            XhCol.AllowDBNull = false;
            XhCol.Unique = false;

            DataColumn YccwCol = dTable.Columns.Add("criterion", typeof(String));
            YccwCol.AllowDBNull = false;
            YccwCol.Unique = false;

            dTable.Columns.Add("CW", typeof(String));
            dTable.Columns.Add("CH", typeof(String));
            dTable.Columns.Add("DJSD1", typeof(Double));
            dTable.Columns.Add("DJSD2", typeof(Double));
            dTable.Columns.Add("HD", typeof(Double));
            dTable.Columns.Add("YCZB", typeof(Double));
            dTable.Columns.Add("RCYL", typeof(Double));
            dTable.Columns.Add("RCQL", typeof(Double));
            dTable.Columns.Add("RCSL", typeof(Double));
            dTable.Columns.Add("SYJL", typeof(String));
            dTable.Columns.Add("JSJG", typeof(String));



            //原始数据获取
            DataSet dsXmkAS01Data = (DataSet)this.FpSpreadXMKAS01.ActiveSheetView.DataSource;
            DataTable dtXmkAS01Data = dsXmkAS01Data.Tables[0];

            //井号获取
            ArrayList JhArrLst = new ArrayList();
            foreach (DataRow dCurRow in dtXmkAS01Data.Rows)
            {
                string strCurJH = dCurRow["JH"].ToString();

                if (!IsAdded(strCurJH, JhArrLst))
                {
                    JhArrLst.Add(strCurJH);
                }
            }

            //条件过滤选取
            string strFilter = "";

            DataRow[] dJhRows = dsXmkAS01Data.Tables[0].Select(strFilter);

            //this.showMessage("有" + JhArrLst.Count + "口井需要统计" + "" + "\n待计算行为" + dtXmkAS01Data.Rows.Count + "。");

            for (int i = 0; i < JhArrLst.Count; i++)
            {
                string strCurJH = JhArrLst[i].ToString();
                //当前井号过滤
                strFilter = string.Format("JH='{0}'", strCurJH);
                DataRow[] dJhRow = dtXmkAS01Data.Select(strFilter);

                //获取当前井号级别最小值
                int minJB = GetMinRowByJB(dJhRow);

                //根据井号和级别值在进行过滤
                strFilter = string.Format("JH='{0}' And JB={1}", strCurJH, minJB);
                dJhRow = dtXmkAS01Data.Select(strFilter);

                //如果只有一个最小值，则把相关该数据存储到井位优选里面去
                if (dJhRow.Length == 1)
                {
                    DataRow dNewRow = dTable.NewRow();
                    dNewRow["JH"] = dJhRow[0]["JH"] != null ? dJhRow[0]["JH"].ToString() : "";
                    dNewRow["XH"] = dJhRow[0]["XH"] != null ? dJhRow[0]["XH"].ToString() : "";
                    dNewRow["criterion"] = dJhRow[0]["criterion"] != null ? dJhRow[0]["criterion"].ToString() : "";
                    dNewRow["CW"] = dJhRow[0]["CW"] != null ? dJhRow[0]["CW"].ToString() : "";
                    dNewRow["CH"] = dJhRow[0]["CH"] != null ? dJhRow[0]["CH"].ToString() : "";
                    dNewRow["DJSD1"] = dJhRow[0]["DJSD1"] != null ? dJhRow[0]["DJSD1"].ToString() : "";
                    dNewRow["DJSD2"] = dJhRow[0]["DJSD2"] != null ? dJhRow[0]["DJSD2"].ToString() : "";
                    dNewRow["YCZB"] = dJhRow[0]["YCZB"] != null ? dJhRow[0]["YCZB"].ToString() : "";
                    dNewRow["HD"] = dJhRow[0]["HD"] != null ? dJhRow[0]["HD"].ToString() : "";
                    dNewRow["RCYL"] = dJhRow[0]["RCYL"] != null ? dJhRow[0]["RCYL"].ToString() : "";
                    dNewRow["RCQL"] = dJhRow[0]["RCQL"] != null ? dJhRow[0]["RCQL"].ToString() : "";
                    dNewRow["RCSL"] = dJhRow[0]["RCSL"] != null ? dJhRow[0]["RCSL"].ToString() : "";
                    dNewRow["SYJL"] = dJhRow[0]["SYJL"] != null ? dJhRow[0]["SYJL"].ToString() : "";
                    dNewRow["JSJG"] = dJhRow[0]["JSJG"] != null ? dJhRow[0]["JSJG"].ToString() : "";
                    dTable.Rows.Add(dNewRow);
                }
                else if (dJhRow.Length > 1) ////如果该井号最小级别有多个，则根据该预定比对字段列对选取最优行
                {
                    string COMPARE = "";
                    double RCLMax = GetMaxValueByCompare(dJhRow, out COMPARE);
                    if (COMPARE != "-") //不是干层
                    {
                        strFilter = string.Format("JH='{0}' And JB={1} And {2}={3}", strCurJH, minJB, COMPARE, RCLMax);
                        dJhRow = dtXmkAS01Data.Select(strFilter);

                        DataRow dNewRow = dTable.NewRow();
                        dNewRow["JH"] = dJhRow[0]["JH"] != null ? dJhRow[0]["JH"].ToString() : "";
                        dNewRow["XH"] = dJhRow[0]["XH"] != null ? dJhRow[0]["XH"].ToString() : "";
                        dNewRow["criterion"] = dJhRow[0]["criterion"] != null ? dJhRow[0]["criterion"].ToString() : "";
                        dNewRow["CW"] = dJhRow[0]["CW"] != null ? dJhRow[0]["CW"].ToString() : "";
                        dNewRow["CH"] = dJhRow[0]["CH"] != null ? dJhRow[0]["CH"].ToString() : "";
                        dNewRow["DJSD1"] = dJhRow[0]["DJSD1"] != null ? dJhRow[0]["DJSD1"].ToString() : "";
                        dNewRow["DJSD2"] = dJhRow[0]["DJSD2"] != null ? dJhRow[0]["DJSD2"].ToString() : "";
                        dNewRow["YCZB"] = dJhRow[0]["YCZB"] != null ? dJhRow[0]["YCZB"].ToString() : "";
                        dNewRow["HD"] = dJhRow[0]["HD"] != null ? dJhRow[0]["HD"].ToString() : "";
                        dNewRow["RCYL"] = dJhRow[0]["RCYL"] != null ? dJhRow[0]["RCYL"].ToString() : "";
                        dNewRow["RCQL"] = dJhRow[0]["RCQL"] != null ? dJhRow[0]["RCQL"].ToString() : "";
                        dNewRow["RCSL"] = dJhRow[0]["RCSL"] != null ? dJhRow[0]["RCSL"].ToString() : "";
                        dNewRow["SYJL"] = dJhRow[0]["SYJL"] != null ? dJhRow[0]["SYJL"].ToString() : "";
                        dNewRow["JSJG"] = dJhRow[0]["JSJG"] != null ? dJhRow[0]["JSJG"].ToString() : "";
                        dTable.Rows.Add(dNewRow);
                    }
                    else  //是干层取任一层就可以
                    {
                        DataRow dNewRow = dTable.NewRow();
                        dNewRow["JH"] = dJhRow[0]["JH"] != null ? dJhRow[0]["JH"].ToString() : "";
                        dNewRow["XH"] = dJhRow[0]["XH"] != null ? dJhRow[0]["XH"].ToString() : "";
                        dNewRow["criterion"] = dJhRow[0]["criterion"] != null ? dJhRow[0]["criterion"].ToString() : "";
                        dNewRow["CW"] = dJhRow[0]["CW"] != null ? dJhRow[0]["CW"].ToString() : "";
                        dNewRow["CH"] = dJhRow[0]["CH"] != null ? dJhRow[0]["CH"].ToString() : "";
                        dNewRow["DJSD1"] = dJhRow[0]["DJSD1"] != null ? dJhRow[0]["DJSD1"].ToString() : "";
                        dNewRow["DJSD2"] = dJhRow[0]["DJSD2"] != null ? dJhRow[0]["DJSD2"].ToString() : "";
                        dNewRow["YCZB"] = dJhRow[0]["YCZB"] != null ? dJhRow[0]["YCZB"].ToString() : "";
                        dNewRow["HD"] = dJhRow[0]["HD"] != null ? dJhRow[0]["HD"].ToString() : "";
                        dNewRow["RCYL"] = dJhRow[0]["RCYL"] != null ? dJhRow[0]["RCYL"].ToString() : "";
                        dNewRow["RCQL"] = dJhRow[0]["RCQL"] != null ? dJhRow[0]["RCQL"].ToString() : "";
                        dNewRow["RCSL"] = dJhRow[0]["RCSL"] != null ? dJhRow[0]["RCSL"].ToString() : "";
                        dNewRow["SYJL"] = dJhRow[0]["SYJL"] != null ? dJhRow[0]["SYJL"].ToString() : "";
                        dNewRow["JSJG"] = dJhRow[0]["JSJG"] != null ? dJhRow[0]["JSJG"].ToString() : "";
                        dTable.Rows.Add(dNewRow);
                    }

                }
                else
                {
                    //Debug.WriteLine(dJhRow.Length);
                }
            }

            this.dsXmk_JH_AS01 = new DataSet();

            this.dsXmk_JH_AS01.Tables.Add(dTable);

            //计算结果相关控件显示
            btnSaveJH.Enabled = true;
            rblJH.Enabled = true;
            btnDownloadJH.Enabled = true;
            FpSpreadJH_XMKAS01.Visible = true;

            //          this.DataGrid1.DataSource = dsXmk_JH_AS01.Tables[0].DefaultView;
            //			this.DataGrid1.DataBind();
            InitSpreadForXmk_JH_As01();

        }
        /// <summary>
        /// 根据该工业级别的比对列比对出当前行的值
        /// </summary>
        /// <param name="dJhRow"></param>
        /// <returns></returns>
        private double GetMaxValueByCompare(DataRow[] dJhRow, out string COMPARE)
        {
            COMPARE = dJhRow[0]["COMPARE"].ToString();

            if (COMPARE.Trim() == "-")
                return 0;
            double dMaxRCL = Convert.ToDouble(dJhRow[0][COMPARE.Trim()]);

            for (int i = 1; i < dJhRow.Length; i++)
            {
                if (dMaxRCL < Convert.ToDouble(dJhRow[i][COMPARE.Trim()]))
                {
                    dMaxRCL = Convert.ToDouble(dJhRow[i][COMPARE.Trim()]);
                }
            }
            return dMaxRCL;
        }

        /// <summary>
        /// 显示井号优选结果
        /// </summary>
        private void InitSpreadForXmk_JH_As01()
        {
            this.modelXmk_JH_As01 = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(dsXmk_JH_AS01, "");
            this.FpSpreadJH_XMKAS01.Sheets[0].DataModel = modelXmk_JH_As01;
            this.FpSpreadJH_XMKAS01.DataBind();

            FpSpreadJH_XMKAS01.ActiveSheetView.AllowSort = true;
            FpSpreadJH_XMKAS01.ActiveSheetView.SetColumnSortIndicator(1, FarPoint.Web.Spread.Model.SortIndicator.Descending);

            FpSpreadJH_XMKAS01.Sheets[0].AllowDelete = true;
            FpSpreadJH_XMKAS01.Sheets[0].AllowInsert = true;
        }
        /// <summary>
        /// 得到当前级别最小值
        /// </summary>
        /// <param name="dJhRow"></param>
        /// <returns></returns>
        private int GetMinRowByJB(DataRow[] dJhRow)
        {
            int minJB = 0;
            if (dJhRow.Length != 0)
                minJB = Convert.ToInt32(dJhRow[0]["JB"]);
            for (int i = 1; i < dJhRow.Length; i++)
            {
                int curRowJB = Convert.ToInt32(dJhRow[i]["JB"]);

                if (minJB > curRowJB)
                {
                    minJB = curRowJB;
                }
            }
            return minJB;
        }

        /// <summary>
        /// 判断当前井号是否添加
        /// </summary>
        /// <param name="jh"></param>
        /// <param name="jhArrLst"></param>
        /// <returns></returns>
        private bool IsAdded(string jh, ArrayList jhArrLst)
        {
            for (int i = 0; i < jhArrLst.Count; i++)
            {
                if (jh == jhArrLst[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }


        #endregion

        #region 按层位优选试油结论数据
        private void btnDownloadCW_Click(object sender, System.EventArgs e)
        {
            string pathName = HttpContext.Current.Server.MapPath(Request.ApplicationPath + "/") + System.Configuration.ConfigurationSettings.AppSettings["tmpDown"].ToString() + "/" + Session["UserCode"].ToString() + "/";
            if (!Directory.Exists(pathName))
            {
                Directory.CreateDirectory(pathName);
            }

            string strFileName = pathName + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + "." + rblCW.SelectedValue;

            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
            }

            bool bSaved = false;
            if (rblCW.SelectedValue == "xls")
            {

                //自带表头
                bSaved = this.FpSpreadCW_XMKAS01.SaveExcel(strFileName, FarPoint.Web.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly);

                //特殊处理带表头
                //				DataGrid drgCase_temp = new DataGrid() ;
                //                DataSet dsDownData = (DataSet)this.FpSpreadXMKAS01.ActiveSheetView.DataSource;
                //				drgCase_temp.DataSource = dsDownData.Tables[0].DefaultView;
                //                drgCase_temp.DataBind();
                //				ExportDataGrid(drgCase_temp,"application/ms-excel",DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")+".xls"); 

            }
            else
            {
                bSaved = this.FpSpreadCW_XMKAS01.ActiveSheetView.SaveTextFile(strFileName, false, FarPoint.Web.Spread.Model.IncludeHeaders.ColumnHeadersCustomOnly, "\r", ";", "");
            }

            if (bSaved)
            {
                //下载传输文件
                string szFileName = Path.GetFileNameWithoutExtension(strFileName);
                strFileName = strFileName.Replace("\\", "*").Replace("/", "*").Replace(" ", "-");
                string strDownUrl = "../CommonPage/DownFile.aspx?FileName='+escape('" + szFileName + "')" + "+'&'+" + "'FilePath=' +escape('" + strFileName + "')";
                Response.Write("<script language='javascript'>window.open('" + strDownUrl + ",'_blank','toolbar=no,directories=no,menubar=no,status=no,width=1,height=1,left=0,top=0');</script>");
            }
            else
            {
                this.showMessage("服务器写文件出现错误，请联系软件技术支持检查文件是否可写或代码错误");
            }
        }



        private void btnCW_Click(object sender, System.EventArgs e)
        {
            //计算结果相关控件显示
            btnSaveCW.Enabled = true;
            rblCW.Enabled = true;
            btnDownloadCW.Enabled = true;

            FpSpreadCW_XMKAS01.Visible = true;

            //准备数据表存储
            DataTable dTable = new DataTable("Xmk_Temp_As01");

            DataColumn JhCol = dTable.Columns.Add("JH", typeof(String));
            JhCol.AllowDBNull = false;
            JhCol.Unique = false;

            DataColumn XhCol = dTable.Columns.Add("Xh", typeof(String));
            XhCol.AllowDBNull = false;
            XhCol.Unique = false;

            DataColumn YccwCol = dTable.Columns.Add("criterion", typeof(String));
            YccwCol.AllowDBNull = false;
            YccwCol.Unique = false;

            dTable.Columns.Add("CW", typeof(String));
            dTable.Columns.Add("CH", typeof(String));
            dTable.Columns.Add("DJSD1", typeof(Double));
            dTable.Columns.Add("DJSD2", typeof(Double));
            dTable.Columns.Add("HD", typeof(Double));
            dTable.Columns.Add("YCZB", typeof(Double));
            dTable.Columns.Add("RCYL", typeof(Double));
            dTable.Columns.Add("RCQL", typeof(Double));
            dTable.Columns.Add("RCSL", typeof(Double));
            dTable.Columns.Add("SYJL", typeof(String));
            dTable.Columns.Add("JSJG", typeof(String));



            //原始数据获取
            DataSet dsXmkAS01Data = (DataSet)this.FpSpreadXMKAS01.ActiveSheetView.DataSource;
            DataTable dtXmkAS01Data = dsXmkAS01Data.Tables[0];

            //井号获取
            ArrayList JhArrLst = new ArrayList();
            foreach (DataRow dCurRow in dtXmkAS01Data.Rows)
            {
                string strCurJH = dCurRow["JH"].ToString();

                if (!IsAdded(strCurJH, JhArrLst))
                {
                    JhArrLst.Add(strCurJH);
                }
            }

            //条件过滤选取
            string strFilter = "";

            DataRow[] dJhRows = dsXmkAS01Data.Tables[0].Select(strFilter);

            //this.showMessage("有" + JhArrLst.Count + "口井需要统计" + "" + "\n待计算行为" + dtXmkAS01Data.Rows.Count + "。");

            for (int i = 0; i < JhArrLst.Count; i++)
            {
                string strCurJH = JhArrLst[i].ToString();
                //当前井号过滤
                strFilter = string.Format("JH='{0}'", strCurJH);
                DataRow[] dJhRow = dtXmkAS01Data.Select(strFilter);

                //获取当前井位的层位序列
                ArrayList JhCwArrLst = GetCWByJH(dJhRow);

                for (int nCw = 0; nCw < JhCwArrLst.Count; nCw++)
                {
                    //根据当前井号，当前层位获取级别值
                    strFilter = string.Format("JH='{0}'  And criterion='{1}'", strCurJH, JhCwArrLst[nCw].ToString());
                    dJhRow = dtXmkAS01Data.Select(strFilter);

                    //获取当前井号级别最小值
                    int minJB = GetMinRowByJB(dJhRow);

                    //根据井号和级别值在进行过滤
                    strFilter = string.Format("JH='{0}' And JB={1} And criterion='{2}'", strCurJH, minJB, JhCwArrLst[nCw].ToString());
                    dJhRow = dtXmkAS01Data.Select(strFilter);

                    //如果只有一个最小值，则把相关该数据存储到井位优选里面去
                    if (dJhRow.Length == 1)
                    {
                        DataRow dNewRow = dTable.NewRow();
                        dNewRow["JH"] = dJhRow[0]["JH"] != null ? dJhRow[0]["JH"].ToString() : "";
                        dNewRow["XH"] = dJhRow[0]["XH"] != null ? dJhRow[0]["XH"].ToString() : "";
                        dNewRow["criterion"] = dJhRow[0]["criterion"] != null ? dJhRow[0]["criterion"].ToString() : "";
                        dNewRow["CW"] = dJhRow[0]["CW"] != null ? dJhRow[0]["CW"].ToString() : "";
                        dNewRow["CH"] = dJhRow[0]["CH"] != null ? dJhRow[0]["CH"].ToString() : "";
                        dNewRow["DJSD1"] = dJhRow[0]["DJSD1"] != null ? dJhRow[0]["DJSD1"].ToString() : "";
                        dNewRow["DJSD2"] = dJhRow[0]["DJSD2"] != null ? dJhRow[0]["DJSD2"].ToString() : "";
                        dNewRow["YCZB"] = dJhRow[0]["YCZB"] != null ? dJhRow[0]["YCZB"].ToString() : "";
                        dNewRow["HD"] = dJhRow[0]["HD"] != null ? dJhRow[0]["HD"].ToString() : "";
                        dNewRow["RCYL"] = dJhRow[0]["RCYL"] != null ? dJhRow[0]["RCYL"].ToString() : "";
                        dNewRow["RCQL"] = dJhRow[0]["RCQL"] != null ? dJhRow[0]["RCQL"].ToString() : "";
                        dNewRow["RCSL"] = dJhRow[0]["RCSL"] != null ? dJhRow[0]["RCSL"].ToString() : "";
                        dNewRow["SYJL"] = dJhRow[0]["SYJL"] != null ? dJhRow[0]["SYJL"].ToString() : "";
                        dNewRow["JSJG"] = dJhRow[0]["JSJG"] != null ? dJhRow[0]["JSJG"].ToString() : "";
                        dTable.Rows.Add(dNewRow);
                    }
                    else if (dJhRow.Length > 1) //如果该井号最小级别有多个，则根据该预定比对字段列对选取最优行
                    {
                        string COMPARE = "";
                        double RCLMax = GetMaxValueByCompare(dJhRow, out COMPARE);
                        if (COMPARE != "-")
                        {
                            strFilter = string.Format("JH='{0}' And JB={1} And {2}={3} And criterion='{4}'", strCurJH, minJB, COMPARE, RCLMax, JhCwArrLst[nCw].ToString());
                            dJhRow = dtXmkAS01Data.Select(strFilter);

                            DataRow dNewRow = dTable.NewRow();
                            dNewRow["JH"] = dJhRow[0]["JH"] != null ? dJhRow[0]["JH"].ToString() : "";
                            dNewRow["XH"] = dJhRow[0]["XH"] != null ? dJhRow[0]["XH"].ToString() : "";
                            dNewRow["criterion"] = dJhRow[0]["criterion"] != null ? dJhRow[0]["criterion"].ToString() : "";
                            dNewRow["CW"] = dJhRow[0]["CW"] != null ? dJhRow[0]["CW"].ToString() : "";
                            dNewRow["CH"] = dJhRow[0]["CH"] != null ? dJhRow[0]["CH"].ToString() : "";
                            dNewRow["DJSD1"] = dJhRow[0]["DJSD1"] != null ? dJhRow[0]["DJSD1"].ToString() : "";
                            dNewRow["DJSD2"] = dJhRow[0]["DJSD2"] != null ? dJhRow[0]["DJSD2"].ToString() : "";
                            dNewRow["YCZB"] = dJhRow[0]["YCZB"] != null ? dJhRow[0]["YCZB"].ToString() : "";
                            dNewRow["HD"] = dJhRow[0]["HD"] != null ? dJhRow[0]["HD"].ToString() : "";
                            dNewRow["RCYL"] = dJhRow[0]["RCYL"] != null ? dJhRow[0]["RCYL"].ToString() : "";
                            dNewRow["RCQL"] = dJhRow[0]["RCQL"] != null ? dJhRow[0]["RCQL"].ToString() : "";
                            dNewRow["RCSL"] = dJhRow[0]["RCSL"] != null ? dJhRow[0]["RCSL"].ToString() : "";
                            dNewRow["SYJL"] = dJhRow[0]["SYJL"] != null ? dJhRow[0]["SYJL"].ToString() : "";
                            dNewRow["JSJG"] = dJhRow[0]["JSJG"] != null ? dJhRow[0]["JSJG"].ToString() : "";
                            dTable.Rows.Add(dNewRow);
                        }
                        else
                        {
                            DataRow dNewRow = dTable.NewRow();
                            dNewRow["JH"] = dJhRow[0]["JH"] != null ? dJhRow[0]["JH"].ToString() : "";
                            dNewRow["XH"] = dJhRow[0]["XH"] != null ? dJhRow[0]["XH"].ToString() : "";
                            dNewRow["criterion"] = dJhRow[0]["criterion"] != null ? dJhRow[0]["criterion"].ToString() : "";
                            dNewRow["CW"] = dJhRow[0]["CW"] != null ? dJhRow[0]["CW"].ToString() : "";
                            dNewRow["CH"] = dJhRow[0]["CH"] != null ? dJhRow[0]["CH"].ToString() : "";
                            dNewRow["DJSD1"] = dJhRow[0]["DJSD1"] != null ? dJhRow[0]["DJSD1"].ToString() : "";
                            dNewRow["DJSD2"] = dJhRow[0]["DJSD2"] != null ? dJhRow[0]["DJSD2"].ToString() : "";
                            dNewRow["YCZB"] = dJhRow[0]["YCZB"] != null ? dJhRow[0]["YCZB"].ToString() : "";
                            dNewRow["HD"] = dJhRow[0]["HD"] != null ? dJhRow[0]["HD"].ToString() : "";
                            dNewRow["RCYL"] = dJhRow[0]["RCYL"] != null ? dJhRow[0]["RCYL"].ToString() : "";
                            dNewRow["RCQL"] = dJhRow[0]["RCQL"] != null ? dJhRow[0]["RCQL"].ToString() : "";
                            dNewRow["RCSL"] = dJhRow[0]["RCSL"] != null ? dJhRow[0]["RCSL"].ToString() : "";
                            dNewRow["SYJL"] = dJhRow[0]["SYJL"] != null ? dJhRow[0]["SYJL"].ToString() : "";
                            dNewRow["JSJG"] = dJhRow[0]["JSJG"] != null ? dJhRow[0]["JSJG"].ToString() : "";
                            dTable.Rows.Add(dNewRow);
                        }
                    }
                    else
                    {
                        //Debug.WriteLine(dJhRow.Length);
                    }
                }
            }

            this.dsXmk_CW_AS01 = new DataSet();

            this.dsXmk_CW_AS01.Tables.Add(dTable);

            InitSpreadForXmk_CW_As01();

        }

        /// <summary>
        /// 根据当前井号得到该井号所有相关的试油层位
        /// 且该层位是标准层位
        /// </summary>
        /// <returns></returns>
        private ArrayList GetCWByJH(DataRow[] dJhRow)
        {
            ArrayList JhCwArrLst = new ArrayList();

            for (int i = 0; i < dJhRow.Length; i++)
            {
                string strCurJHCW = dJhRow[i]["criterion"].ToString();

                if (!IsAdded(strCurJHCW, JhCwArrLst))
                {
                    JhCwArrLst.Add(strCurJHCW);
                }
            }
            return JhCwArrLst;
        }

        /// <summary>
        /// 显示井号优选结果
        /// </summary>
        private void InitSpreadForXmk_CW_As01()
        {
            this.modelXmk_CW_As01 = new FarPoint.Web.Spread.Model.DefaultSheetDataModel(this.dsXmk_CW_AS01, "");
            this.FpSpreadCW_XMKAS01.Sheets[0].DataModel = modelXmk_CW_As01;
            this.FpSpreadCW_XMKAS01.DataBind();

            FpSpreadCW_XMKAS01.ActiveSheetView.AllowSort = true;
            FpSpreadCW_XMKAS01.ActiveSheetView.SetColumnSortIndicator(1, FarPoint.Web.Spread.Model.SortIndicator.Descending);

            FpSpreadCW_XMKAS01.Sheets[0].AllowDelete = true;
            FpSpreadCW_XMKAS01.Sheets[0].AllowInsert = true;
        }
        #endregion
    }
}